package com.sinog.front.controller.biz;

import com.sinog.core.model.UploadAppendixFile;
import com.sinog.core.model.UserDTO;
import com.sinog.core.util.JsonUtil;
import com.sinog.core.utilbean.Constants;
import com.sinog.core.utilbean.Result;
import com.sinog.core.utilbean.ReturnCode;
import com.sinog.front.config.idempotent.Idempotent;
import com.sinog.front.config.log.Log;
import com.sinog.front.feign.biz.BaseInfoService;
import com.sinog.front.feign.biz.SearchCodeList;
import com.sinog.front.feign.biz.SecXxxjService;
import com.sinog.front.feign.biz.XxblService;
import com.sinog.front.service.azbj.uploadappendix.UploadAppendixFileService;
import com.sinog.front.service.user.UserFacade;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @desc 预安置管理 - 预释放人员衔接
 * @author -
 * @date -
 */
@RestController
public class AbryXjController {

    @Autowired
    private UserFacade userService;
    @Resource
    private BaseInfoService baseInfoService;
    @Autowired
    private UploadAppendixFileService uploadAppendixService;
    @Resource
    private XxblService xxblService;
    @Resource
    private SearchCodeList searchCodeList;
    @Resource
    private SecXxxjService secXxxjService;

    /**
     * 预安置管理 - 预释放人员衔接 - (补录信息、待衔接、衔接中、已衔接、衔接失败) - 列表数据
     * @param searchMap 搜索条件
     * @return String
     */
    @RequestMapping("/yazgl/xjxx/xxbl/list")
    public String toXxblPublicList(@RequestParam(required = false) Map<String,Object> searchMap) {
        //获取用户信息
        UserDTO user = userService.getAuthentication();
        return baseInfoService.getXxblList(user,searchMap);
    }

    /**
     * 预安置管理 - 预释放人员衔接 - (未衔接) - 列表数据
     * @param searchMap 搜索条件
     * @return String
     */
    @RequestMapping("/yazgl/xjxx/wxj/list")
    public String toWxjPublicList(@RequestParam(required = false) Map<String,Object> searchMap) {
        //获取用户信息
        UserDTO user = userService.getAuthentication();
        return baseInfoService.getWxjList(user,searchMap);
    }

    /**
     * 衔接 - 信息补录 - 减刑假释信息录入保存
     * 保存的是本次的刑期止日
     * pri_stop_old为上一次的刑期止日
     * @param request request
     * @param data data
     * @return Result
     */
    @Log(type = "新增", value = "新增减刑假释信息")
    @Idempotent(paramPos = 1)
    @PostMapping("/azbj/yazgl/xxbl/jxjs/save")
    public Result saveJxjsInfo(HttpServletRequest request,String data) {
        UserDTO user = userService.getAuthentication();
        //String 转map
        Map<String,Object> map = JsonUtil.toMap(data);
        return xxblService.saveJxjsInfo(map,user);
    }

    /**
     * 衔接 - 信息补录 - 减刑假释信息列表
     * @param pageIndex pageIndex
     * @param pageSize pageSize
     * @param priNum priNum
     * @return Object
     */
    @RequestMapping("/azbj/yazgl/xxbl/jxjs/list")
    public Object jxjsInfoList(Integer pageIndex,Integer pageSize,String priNum) {
        return xxblService.jxjsInfoList(pageIndex,pageSize,priNum);
    }

    /**
     * 衔接 - 信息录入 - 减刑假释信息删除
     * @param request request
     * @param priNum priNum
     * @return Result
     */
    @Log(type = "删除", value = "删除减刑假释信息")
    @PostMapping("/azbj/yazgl/xxbl/jxjs/delete")
    public Result jxjsInfoDelete(HttpServletRequest request,String priNum) {
        UserDTO user = userService.getAuthentication();
        String account = user.getAccount();
        return xxblService.jxjsInfoDelete(priNum,account);
    }

    /**
     * 衔接 - 信息补录 - 保存职业技能
     * @param request request
     * @param data data
     * @return Result
     */
    @Log(type = "更新", value = "更新职业技能信息")
    @PostMapping("/azbj/yazgl/xxbl/zyjn/save")
    public Result saveZyjnInfo(HttpServletRequest request,String data) {
        UserDTO user = userService.getAuthentication();
        return xxblService.saveZyjnInfo(data,user);
    }


    /**
     * 衔接 - 信息补录 - 职业技能信息列表
     * @param pageIndex pageIndex
     * @param pageSize pageSize
     * @param priNum priNum
     * @return Object
     */
    @RequestMapping("/azbj/yazgl/xxbl/zyjn/list")
    public Object zyjnInfoList(Integer pageIndex,Integer pageSize,String priNum) {
        //todo 这种判断尽量说明原因，解决问题从源头解决，为什么犯罪编号会空？
        if(StringUtils.isEmpty(priNum)) {
            return null;
        }
        return xxblService.zyjnInfoList(pageIndex,pageSize,priNum);
    }

    /**
     * 衔接 - 信息录入 - 查询职业技能详情
     * @param codeType codeType
     * @param pcodeId pcodeId
     * @return List<Map < String,Object>>
     */
    @RequestMapping("/search/code/zyjn")
    public List<Map<String,Object>> echoZyjn(
            @RequestParam(required = false) String codeType,@RequestParam(required = false) String pcodeId) {
        boolean go = StringUtils.isAnyBlank(pcodeId,codeType);
        return go ? null : searchCodeList.echozyjnValue(codeType,pcodeId);
    }

    /**
     * 衔接 - 信息录入 - 职业技能信息删除
     * @param request request
     * @param id id
     * @return int
     */
    @Log(type = "删除", value = "删除职业技能信息")
    @PostMapping("/azbj/yazgl/xxbl/zyjn/remove")
    public int zyjnInfoDelete(HttpServletRequest request,String id) {
        return xxblService.zyjnInfoDelete(id);
    }

    @Log(type = "更新", value = "更新危险评估信息")
    @PostMapping("/azbj/wxxpg/update")
    public Result updateSentenceInfo(HttpServletRequest request,@RequestParam String data) {
        Result cjpgResult;
        Map<String,Object> jsonMap = JsonUtil.toMap(data);
        if(CollectionUtils.isEmpty(jsonMap)) {
            return Result.failure(ReturnCode.UPDATE_FAILED);
        }
        cjpgResult = baseInfoService.updateCjpg(jsonMap);
        if(Constants.Number.NUM_ONE.equals( cjpgResult.getCode())) {
            return Result.success();
        } else {
            return Result.failure(ReturnCode.UPDATE_FAILED);
        }
    }

    /**
     * 衔接- 信息补录 - 保存/更新 出监/危险评估信息
     * @param request request
     * @param data 出监评估信息
     * @return Result
     */
    @Log(type = "新增", value = "保存危险评估信息")
    @Idempotent(paramPos = 1)
    @PostMapping("/azbj/wxxpg/save")
    public Result saveSentenceInfo(HttpServletRequest request,@RequestParam String data) {
        UserDTO userDTO = userService.getAuthentication();
        //参数转换
        Map<String,Object> jsonMap = JsonUtil.toMap(data);
        Result cjpgResult;
        String userDtoStr = JsonUtil.toText(userDTO);
        jsonMap.put("userDTO",userDtoStr);
        //根据犯罪编号查询prisoner_cjpg表是否存在数据
        String cjpgInfo = xxblService.selectCjpgInfoByPrNum(jsonMap.get("priNum").toString());
        Map<String,Object> cjpgInfoMap = JsonUtil.toMap(cjpgInfo);
        //数据库中存在该犯罪编号的数据，更新prisoner_cjpg，否则新增prisoner_cjpg
        if(null != cjpgInfoMap) {
            jsonMap.put("updateTime",new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
            jsonMap.put("updateUser",userDTO.getAccount());
            cjpgResult = baseInfoService.updateCjpg(jsonMap);
        } else {
            cjpgResult = baseInfoService.insertCjpg(jsonMap);
        }
        //prisoner_cjpg表处理成功后，更新服刑表
        if(Constants.Number.NUM_ONE.equals(cjpgResult.getCode())) {
            return xxblService.saveWxxpgInfo(data,userDTO.getAccount());
        } else {
            return Result.failure(ReturnCode.SAVE_FAILED);
        }
    }

    /**
     * 衔接信息的插入
     * @param request request
     * @param data data
     * @return Integer
     */
    @Log(type = "新增", value = "发起衔接")
    @Idempotent(paramPos = 1)
    @PostMapping("/azbj/yazgl/xj/insert")
    public Result insertXjxx(HttpServletRequest request,String data) {
        //查询流程中上传表单所有服务器端文件
        UserDTO userDto = userService.getAuthentication();
        String departid = userDto.getDepartid();
        String departName = userDto.getDepartName();
        String account = userDto.getAccount();
        return baseInfoService.insertXjxx(data,departid,departName,account);
    }

    /**
     * 衔接中 - 发送回执消息
     * @param request request
     * @param data data
     * @return Result
     */
    @Log(type = "新增", value = "发送回执消息")
    @Idempotent(paramPos = 1)
    @PostMapping(value = "/azbj/yazgl/xj/hz/savemessage")
    public Result saveXjHzMessage(HttpServletRequest request,String data) {
        Map<String,Object> hashMap = new HashMap<>(16);
        UserDTO userDTO = userService.getAuthentication();
        //将核查唯一标识写到Result中
        String xjrctId = baseInfoService.saveXjHzMessage(data,userDTO.getAccount(),userDTO.getLevel());
        hashMap.put("userDTO",userDTO);
        hashMap.put("xjrctId",xjrctId);
        return Result.success(hashMap);
    }

    /**
     * 衔接中 - 查看回执列表数据
     * @param priNum priNum
     * @return String
     */
    @RequestMapping(value = "/azbj/xj/hz/listMessages", method = RequestMethod.GET)
    public String findMessages(@RequestParam(value = "priNum") String priNum,@RequestParam(required = false, defaultValue = "-1") String xjrctId) {
        //根据犯罪编号查询
        return baseInfoService.findMessages(priNum,xjrctId);
    }

    /**
     * 衔接 - 完成衔接更新状态
     * @param request request
     * @param data data
     * @param flag 1:通知公安机关落实管控措施 选择是
     * @return Result
     */
    @Log(type = "新增", value = "完成衔接")
    @Idempotent(paramPos = {1,2})
    @PostMapping("/azbj/yazgl/xj/save/fj")
    public Result updateCompletelyData(HttpServletRequest request,String data,
                                       @RequestParam(required = false) String flag) {
        //如果 通知公安机关落实管控措施 选择是，则需要检查是否上传附件
        if(Constants.NumberStr.NUM_STR_ONE.equals(flag)) {
            //查询 通知公安机关落实管控措施 附件
            Map<String,Object> jsonMapTemp = JsonUtil.toMap(data);
            jsonMapTemp.put("taskId",Constants.Number.NUM_TEN_ONE);
            List<UploadAppendixFile> galist = uploadAppendixService.selectAllAppendixFile(0,10,jsonMapTemp);
            if(galist.isEmpty()) {
                return Result.failure(ReturnCode.NO_ASSESSORY);
            }
        }
        Map<String,Object> jsonMap = JsonUtil.toMap(data);
        List<UploadAppendixFile> list = uploadAppendixService.selectAllAppendixFile(0,10,jsonMap);
        String statexj = jsonMap.get("statexj").toString();
        if(list.isEmpty() && (!Constants.NumberStr.NUM_STR_THREE.equals(statexj))) {
            return Result.failure(ReturnCode.NO_PROVE);
        }
        UserDTO userDTO = userService.getAuthentication();
        //校验是否上传刑满释放人员通知书    释放刑满释放人员通知书已经取消，可以从已衔接里面进行补录()
        return baseInfoService.updateCompletelyData(data,userDTO);
    }

    /**
     * 转到安置帮教
     * @param priNum priNum
     * @return Result
     */
    @Log(type = "更新", value = "转到安置帮教")
    @Idempotent(paramPos = 1)
    @PostMapping("/azbj/yazgl/xj/move/anzhi")
    public Result moveToAnZhiData(HttpServletRequest request,String priNum) {
        UserDTO user = userService.getAuthentication();
        return baseInfoService.moveToAnZhi(priNum,user);
    }

    /**
     * 衔接失败上报
     * @param request request
     * @param data data
     * @return Result
     */
    @Log(type = "更新", value = "衔接失败上报(id不为空：更新，id为空：新增)")
    @Idempotent(paramPos = 1)
    @PostMapping("/azbj/ysfryxj/xjreport/save")
    public Result saveXjReport(HttpServletRequest request,
                               @RequestParam(defaultValue = "-1", required = false) String data) {
        UserDTO user = userService.getAuthentication();
        return secXxxjService.saveXjReport(data,user);
    }

    /**
     * 监狱重新发起衔接
     * @param request request
     * @param data data
     * @return Result
     */
    @Log(type = "更新", value = "监狱重新发起衔接")
    @Idempotent(paramPos = 1)
    @PostMapping("/azbj/yazgl/xj/updateXj")
    public Result againXjSave(HttpServletRequest request,
                              @RequestParam(defaultValue = "-1", required = false) String data) {
        UserDTO userDTO = userService.getAuthentication();
        String departid = userDTO.getDepartid();
        String departName = userDTO.getDepartName();
        String account = userDTO.getAccount();
        //校验是否上传刑满释放人员通知书    监狱释放前一个月可能拿不到释放人员通知书。(这里将上传ysf人员通知书注释)
        return baseInfoService.updateXjxx(data,departid,departName,account);
    }

    /**
     * todo:需要添加log注解
     * 司法所衔接选择失败后将之前上传的公安附件删除
     * @param priNum priNum
     * @return Result
     */
    @RequestMapping("/azbj/yazgj/xj/deleteUploadFile")
    public Result deleteUploadFile(
            @RequestParam(value = "priNum", required = false) String priNum,
            @RequestParam(value = "id", required = false) String id) {
        return uploadAppendixService.deleteUploadFile(priNum,id);
    }
    /**
     * 山西个性化需求
     * 预安置管理 - 预释放人员衔接 - 信息补录 - 服刑信息变更基本信息添加
     * @param request request
     * @param data data
     * @return Result
     */
    @Log(type = "新增", value = "服刑信息变更，基本信息添加")
    @RequestMapping("/azbj/wxxpg/saveBaseInfo")
    public Result saveSentenceBaseInfo(HttpServletRequest request,@RequestParam String data) {
        Map<String,Object> jsonMap = JsonUtil.toMap(data);
        Map<String,Object> fileMap = new HashMap<>(16);
        fileMap.put("priNum",jsonMap.get("priNum"));
        fileMap.put("amnesty",jsonMap.get("amnesty"));
        fileMap.put("zfz",jsonMap.get("zfz"));
        fileMap.put("death",jsonMap.get("death"));
        if(Constants.NumberStr.NUM_STR_ONE.equals(jsonMap.get("death"))){
            fileMap.put("dateTime",jsonMap.get("dateTime"));
        }
        int result = baseInfoService.updateJbxx(jsonMap);
        if(result > 0){
            return Result.success("保存成功");
        }
        return Result.failure(ReturnCode.SAVE_FAILED);
    }
}